package xls

import (
	"runtime"
	"strconv"

	"gitee.com/yrwy/msgo/pkg/storage"

	"github.com/xuri/excelize/v2"
)

type Store struct {
	w     *excelize.File
	sheet string
	row   int
}

func NewStore(file *excelize.File, sheet string) *Store {
	r := &Store{w: file, sheet: sheet, row: 0}
	rows, err := file.Rows(sheet)
	if err == nil {
		r.row = rows.TotalRows()
	} else {
		file.NewSheet(sheet)
	}
	return r
}

func NewFile(name string, sheet string) (*Store, error) {
	fp, err := excelize.OpenFile(name)
	if err != nil {
		return nil, err
	}
	runtime.SetFinalizer(fp, func(o *excelize.File) {
		o.Save()
		o.Close()
	})
	return NewStore(fp, sheet), nil
}

func (x *Store) GetRow() int {
	return x.row
}

func (x *Store) Write(d storage.IData) error {
	x.row++
	row := d.GetRow()
	return x.w.SetSheetRow(x.sheet, "A"+strconv.Itoa(x.row), &row)
}

func (x *Store) Writes(ds []storage.IData) (int, error) {
	for i, d := range ds {
		err := x.Write(d)
		if err != nil {
			return i, err
		}
	}
	return len(ds), nil
}
